<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}`"
    width="660"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div v-loading="loading">
      <el-form
        ref="formRef"
        :model="formValues"
        :rules="rules"
        label-position="top"
        label-width="120px"
      >
        <el-form-item label="费用标识" prop="cost_ident">
          <el-input v-model="formValues.cost_ident" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="	费用名称" prop="cost_label">
          <el-input v-model="formValues.cost_label" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import {
  tcFeeConfigDetail,
  tcFeeConfigCreate,
  tcFeeConfigUpdate,
} from "../api.js";
const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
});
const rules = reactive({
  cost_ident: [{ required: true, message: "请输入费用标识", trigger: "blur" }],
  cost_label: [{ required: true, message: "请输入费用名称", trigger: "blur" }],
});
const loading = ref(false);
const isEdit = computed(() => {
  return !!props.id;
});
const emit = defineEmits(["update:modelValue", "refresh", "close"]);
watch(
  () => props.id,
  (val) => {
    if (val) {
      nextTick(() => {
        getDetail(val);
      });
    }
  }
);
const getDetail = async (val) => {
  const { data } = await tcFeeConfigDetail({ id: val });
  formValues.value = data || {};
};
const formValues = ref({});
const formRef = ref();
const handleSave = async () => {
  try {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        const { code, message } = await (isEdit.value
          ? tcFeeConfigUpdate
          : tcFeeConfigCreate)(formValues.value);
        if (code != 200) return ElMessage.error(message);
        ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
        handleClose(true);
      } else {
        return false;
      }
    });
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};
const handleClose = async (refresh) => {
  formValues.value = {};
  formRef.value?.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
